<template>
    <div class="app-container client-detail">
        <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="120px">
            <el-collapse v-model="activeNames">
                <el-collapse-item title="基础信息" name="1">
                    <el-col :span="12">
                        <el-form-item label="来源部门" prop="source_department_id">
                            <el-radio v-model="form.source_department_id" label="1">电商部</el-radio>
                            <el-radio v-model="form.source_department_id" label="2">新媒体部</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone_number">
                            <el-input v-model="form.phone_number" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="微信昵称" prop="wechat_nickname">
                            <el-input v-model="form.wechat_nickname" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="微信号" prop="wechat_id">
                            <el-input v-model="form.wechat_id" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-collapse-item>

                <el-collapse-item title="订单信息" name="2">
                    <el-col :span="12">
                        <el-form-item label="来源店铺">
                            <el-cascader style="width: 100%"
                                v-model="form.source_store_id"
                                :options="shopList"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单编号" prop="order_number">
                            <el-input v-model="form.order_number" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="产品名称">
                            <el-select v-model="form.product_id" filterable placeholder="请选择" style="width: 100%" @change="changeProduct">
                                <el-option
                                    v-for="item in productsList"
                                    :key="item.id"
                                    :label="item.product_name + '-' +item.product_norm"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单日期">
                            <el-date-picker 
                                v-model="form.order_date"
                                type="datetime"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss" 
                                align="right" 
                                style="width: 100%"
                                @change="changDateOrder"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收货地址">
                            <el-input v-model="form.consignees_address" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收货人">
                            <el-input v-model="form.consignees" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="购买数量">
                            <el-input v-model.number="form.buy_qty" placeholder="请输入" @change="changeBuyNum" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="购买金额" prop="buy_amount">
                            <el-input v-model.number="form.buy_amount" placeholder="请输入">
                                <font slot="suffix">元</font>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="预估使用日期">
                            <el-date-picker 
                                v-model="form.estimate_use_date" 
                                type="datetime" 
                                align="right" 
                                value-format="yyyy-MM-dd HH:mm:ss" 
                                style="width: 100%" 
                            />
                        </el-form-item>
                    </el-col>
                </el-collapse-item>

                <el-collapse-item title="用户信息" name="3">
                    <el-col :span="12">
                        <el-form-item label="性别">
                            <el-radio-group v-model="form.sex">
                                <el-radio v-for="dict in sexList" :key="dict.id" :label="dict.id">{{ dict.title }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="年龄">
                            <el-radio-group v-model="form.age_range">
                                <el-radio v-for="dict in agesList" :key="dict.id" :label="dict.id">{{ dict.title }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="痛点问题">
                            <el-checkbox v-model="checkAllQues" @change="changeAllQues">全选</el-checkbox>
                            <div style="margin: 15px 0;"></div>
                            <el-checkbox-group v-model="form.pain_points_question" @change="changeIndeterQues">
                                <el-checkbox v-for="item in quesList" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否加微">
                            <el-radio v-model="form.is_add_wechat" label="1">是</el-radio>
                            <el-radio v-model="form.is_add_wechat" label="0">否</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="加微日期">
                            <el-date-picker 
                                v-model="form.add_wechat_date" 
                                type="datetime" 
                                align="right"
                                value-format="yyyy-MM-dd HH:mm:ss" 
                                style="width: 100%" 
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="家庭情况">
                            <el-input type="textarea" v-model="form.family_situation" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="form.notes" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-collapse-item>
                
                <el-collapse-item title="裂变数据" name="4">
                    <el-col :span="12">
                        <el-form-item label="老带新">
                            <el-radio v-model="form.is_customer_referrals" label="0">否</el-radio>
                            <el-radio v-model="form.is_customer_referrals" label="1">是</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="裂变状态">
                            <el-radio v-model="form.mutation_status" label="0">否</el-radio>
                            <el-radio v-model="form.mutation_status" label="1">是</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="裂变质量">
                            <el-radio v-model="form.mutation_level" label="3">高</el-radio>
                            <el-radio v-model="form.mutation_level" label="2">中</el-radio>
                            <el-radio v-model="form.mutation_level" label="1">低</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活跃等级">
                            <el-radio v-model="form.activity_level" label="3">高</el-radio>
                            <el-radio v-model="form.activity_level" label="2">中</el-radio>
                            <el-radio v-model="form.activity_level" label="1">低</el-radio>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="感兴趣产品" prop="age">
                            <el-checkbox v-model="checkAllProd" @change="changeAllProd">全选</el-checkbox>
                            <div style="margin: 15px 0;"></div>
                            <el-checkbox-group v-model="form.interested_products" @change="changeIndeterProd">
                                <el-checkbox v-for="(item, index) in intereList" :label="item.id" :key="index">{{item.name}}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                </el-collapse-item>
            </el-collapse>
        </el-form>
        <el-row type="flex" justify="center">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
        </el-row>
    </div>
</template>

<script>
import { getAges, getShops, getSex, getIntereProd, getPrivaQues } from "@/api/dict";
import { custSubmit, custDetail, getProducts } from "@/api/shop";

export default {
    data() {
        return {
            activeNames: ['1','2','3','4'],
            custID:'',
            form:{
                estimate_use_date:'',
                pain_points_question:[],
                interested_products:[],
                source_department_id:"1"
            },
            rules: {source_department_id: [{ required: true, message: "请选择", trigger: "blur" }]},
            agesList:[],
            checkAllProd:false,
            intereList:[],
            products:{},
            productsList:[],
            sexList:[],
            shopList:[],
            checkAllQues: false,
            quesList:[],
        };
    },
    created() {
        this.getAgesList()
        this.getIntereList()
        this.getSexList()
        this.getShopList()
        this.getProductsList()
        this.getPrivaQuesList()
        if(this.$route.params.id){
            this.custID = this.$route.params.id
            this.getCustDetail()
        }
    },
    methods: {
        getAgesList(){
            getAges().then(res => {
                this.agesList = res.data
            });
        },
        getIntereList(){
            getIntereProd().then(res => {
                this.intereList = res.data
            });
        },
        getSexList(){
            getSex().then(res => {
                this.sexList = res.data
            });
        },
        getShopList(){
            getShops().then(res => {
                const sourceMap = {}
                res.data.forEach(item => {
                    const { source_platform, id, shop_name } = item;
                    if (!sourceMap[source_platform]) {
                        sourceMap[source_platform] = {
                            value: '',
                            label: source_platform,
                            children: []
                        };
                    }
                    sourceMap[source_platform].children.push({
                        value: String(id),
                        label: shop_name
                    });
                });
                // 转换为最终数组格式
                this.shopList = Object.values(sourceMap);
            });
        },
        getProductsList(){
            getProducts().then(res => {
                this.productsList = res.data
            });
        },
        getPrivaQuesList(){
            getPrivaQues().then(res => {
                this.quesList = res.data
            });
        },
        getCustDetail(){
            custDetail({id: this.custID}).then(res => {
                this.form = res.data
                this.form.activity_level = this.form.activity_level.toString()
                this.form.is_customer_referrals = this.form.is_customer_referrals.toString()
                this.form.mutation_level = this.form.mutation_level.toString()
                this.form.mutation_status = this.form.mutation_status.toString()
                this.form.source_department_id = this.form.source_department_id.toString()
                this.form.source_store_id = this.form.source_store_id.toString()
                this.form.is_add_wechat = this.form.is_add_wechat.toString()
                this.products.id = this.form.product_id.toString()

                const convert = s => s.includes(',') ? s.split(',').map(Number) : [Number(s)];
                this.form.interested_products =  convert(this.form.interested_products)
                this.form.pain_points_question =  convert(this.form.pain_points_question) 
                if(this.form.interested_products.length == this.intereList.length){
                    this.checkAllProd = true
                }
                if(this.form.pain_points_question.length == this.quesList.length){
                    this.checkAllQues = true
                }
            });
        },
        changeProduct(val){
            let curProd = this.productsList.find(item => item.id == val)
            this.form.product_name = curProd.product_name
            if(this.form.order_date){
                this.form.estimate_use_date = this.addDays(this.form.order_date, curProd.usage_days);
            }
        },
        addDays(dateStr, days) {
            console.log(dateStr,days)
            const [datePart, timePart] = dateStr.split(' ');
            const [year, month, day] = datePart.split('-').map(Number);
            const date = new Date(year, month - 1, day);
            const num = this.form.buy_qty || 1
            date.setDate(date.getDate() + days * num);
            const pad = n => n.toString().padStart(2, '0');
            return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${timePart}`;
        },
        changDateOrder(e){
            if(this.form.product_id){
                let curProd = this.productsList.find(item => item.id == this.form.product_id)
                this.form.estimate_use_date = this.addDays(e, curProd.usage_days);
            }
        },
        changeBuyNum(){
            if(this.form.product_id){
                let curProd = this.productsList.find(item => item.id == this.form.product_id)
                this.form.estimate_use_date = this.addDays(this.form.order_date, curProd.usage_days);
            }
        },
        changeAllQues(val) {
            let ids = this.quesList.map(item => item.id)
            this.form.pain_points_question = val ? ids : [];
        },
        changeIndeterQues(value) {
            let len = value.length;
            this.checkAllQues = len === this.quesList.length;
        },
        changeAllProd(val) {
            let ids = this.intereList.map(item => item.id)
            this.form.interested_products = val ? ids : []
        },
        changeIndeterProd(value) {
            let len = value.length;
            this.checkAllProd = len === this.intereList.length;
        },
        goBack(){
            this.$router.go(-1)
        },
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    let msg = "新增成功"
                    if(this.form.source_store_id && this.form.source_store_id.length > 1){
                        this.form.source_store_id = this.form.source_store_id[1] 
                    }
                    if(this.custID){
                        this.form.id = this.custID
                        msg = "修改成功"
                    }
                    custSubmit(this.form).then(res => {
                        this.$modal.msgSuccess(msg);
                        this.$router.go(-1)
                    });
                }
            });
        },
    }
};
</script>

<style lang="scss">
    .client-detail {
        .el-collapse{
            border: none;
            .el-collapse-item{margin-bottom: 20px;}
            .el-collapse-item__header{font-size: 16px;font-weight: bold;border-bottom-color: #e6ebf5;margin-bottom: 20px;}
            .el-collapse-item__wrap{border: none;}
        }
        .el-form-item{
            width: 100%;
            .el-form-item__content{width: calc(100% - 120px);}
        }
        .el-radio input[aria-hidden="true"]{display: none!important;}
    }
</style>
